package com.ruge.spring.cloud.gateway.filter;

import com.ruge.spring.cloud.gateway.base.exception.BaseBusinessException;
import com.ruge.spring.cloud.gateway.base.exception.SystemError;
import com.ruge.spring.cloud.gateway.base.response.Response;
import com.ruge.spring.cloud.gateway.base.token.CheckTokenResponse;
import com.ruge.spring.cloud.gateway.config.AppConfig;
import com.ruge.spring.cloud.gateway.dao.ServerAdminClient;
import com.ruge.spring.cloud.gateway.error.ApiGatewayError;
import com.ruge.spring.cloud.gateway.util.UriMatchUtil;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang.StringUtils;
import org.springframework.cloud.gateway.filter.GatewayFilterChain;
import org.springframework.cloud.gateway.filter.GlobalFilter;
import org.springframework.core.Ordered;
import org.springframework.stereotype.Component;
import org.springframework.web.server.ServerWebExchange;
import reactor.core.publisher.Mono;

import javax.annotation.Resource;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
import java.util.Map;

/**
 * @author 嘿丷如歌
 * @version V1.0
 * @Description: 校验admin token的拦截器
 * @date 2021/4/26 21:51
 */
@Slf4j
@Component
public class AdminTokenCheckFilter implements GlobalFilter, Ordered {

    private static volatile List<String> availablePublicPathPattens = null;
    static final String ADMIN_URI_PATTERN = "/**/admin/**,/*/locationAdmin/**";

    @Resource
    private AppConfig appConfig;

    @Resource(name = "serverAdminClientMap")
    private Map<String, ServerAdminClient> clientMap;


    /**
     * Process the Web request and (optionally) delegate to the next {@code WebFilter}
     * through the given {@link GatewayFilterChain}.
     *
     * @param exchange the current server exchange
     * @param chain    provides a way to delegate to the next filter
     * @return {@code Mono<Void>} to indicate when request processing is complete
     */
    @Override
    public Mono<Void> filter(ServerWebExchange exchange, GatewayFilterChain chain) {
        String reqUri = exchange.getRequest().getURI().toString();
        if (appConfig.getAdminTokenCheckWhiteList().contains(reqUri)) {
            // 配置了白名单，且当前请求匹配了白名单
            log.debug("AdminTokenCheckFilter: the uri {} matched whiteList", reqUri);
        } else if (UriMatchUtil.patternUriMatch(availableAdminPathPattens(), reqUri)) {
            // 获取token
            String token = exchange.getRequest().getQueryParams().getFirst("token");
            if (StringUtils.isBlank(token)) {
                throw new BaseBusinessException(ApiGatewayError.TOKEN_NOT_FOND);
            }
            // 根据token前缀，解析出访问的token校验服务名
            String[] splitArr = token.split("---");
            // 如果小于两段，则不符合admin token的规则
            if (splitArr.length < 2) {
                throw new BaseBusinessException(ApiGatewayError.ADMIN_TOKEN_ERROR);
            }
            String tokenPrefix = splitArr[0];

            ServerAdminClient client = clientMap.get(tokenPrefix);
            if (null == client) {
                log.error("Did not configure admin token checker for token prefix :{}", tokenPrefix);
                throw new BaseBusinessException(SystemError.SYSTEM_INTERNAL_ERROR, "admin token checker configure error.");
            }
            // 调用服务校验token
            doCheckToken(token, client);
        }
        return chain.filter(exchange); //继续向下执行
    }

    private void doCheckToken(String token, ServerAdminClient client) {
        try {
            CheckTokenResponse response = client.checkAdminToken(token);
            if (response.getStatus() == Response.Status.FAILED) {
                log.error("AdminToken check failed:\n{}", response);
                throw new BaseBusinessException(response.getErrorCode(), "Admin Token check failed.", response.getErrorMessage());
            } else {
                // token检查成功，设置token对象到header中
                log.debug("checkAdminToken req success.");
            }
        } catch (Exception exception) {
            if (exception instanceof BaseBusinessException) {
                throw exception;
            }
            log.error("Admin Token checker unknown Error.");
            BaseBusinessException ex = new BaseBusinessException(SystemError.SYSTEM_INTERNAL_ERROR);
            ex.setExtMessage("AdminTokenCheckFilter unknown error.");

            throw ex;
        }
    }

    private List<String> availableAdminPathPattens() {
        if (null == availablePublicPathPattens) {
            synchronized (AdminTokenCheckFilter.class) {
                availablePublicPathPattens = new ArrayList<>();
                availablePublicPathPattens.addAll(Arrays.asList(ADMIN_URI_PATTERN.split(",")));
                availablePublicPathPattens.addAll(appConfig.getNonStandardPath().get("admin"));
            }
        }
        return availablePublicPathPattens;
    }

    @Override
    public int getOrder() {
        return 10;
    }
}
